import React from 'react';
import PropTypes from 'prop-types';
import {Form, Card, Button, Row, Col, Spin, Table, Modal} from 'antd';
import {TABLE, DATE_FORMAT} from '../constants';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import {partStatus, currency, partsPriceType, partChannel} from '../Enum';
import routes from './routes';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import styles from './style.css';
import {connect} from 'react-redux';
import * as actions from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {injectIntl} from './intl';
import Ellipsis from 'ant-design-pro/lib/Ellipsis';
import moment from 'moment';

const {Description} = DescriptionList;

class DetailPage extends React.PureComponent {
    state = {
        isSubmitting: false,
        isFetching: false,
        data: {},
        visible: false,
        currentRecord: {}
    }

    componentDidMount() {
        this.asyncQuery(this.props.id);
    }

    handleDetail = e => {
        this.props.history.push(routes.detail.format(e.target.dataset.recordId));
        this.asyncQuery(e.target.dataset.recordId);
    }

    asyncQuery = id => {
        this.setState({isFetching: true});
        this.props.queryInitData(id).then(data => {
            this.setState({isFetching: false});
            if(data)
                this.setState({
                    data
                });
        });
    }

    toggle = () => {
        this.setState(state => ({
            visible: !state.visible
        }));
    }

    afterWarrantyPartTypeConfirm = () => {
        this.props.history.push(routes.query.url());
        this.props.refreshList();
    }

    setClassName = record => record.isEstimated === true && !this.props.isDealerUser ? styles.tableConditionsRow : '';

    render() {
        const {formatMessage} = this.props.intl;
        const Yes = formatMessage({
            id: 'detailPage.yes',
            defaultMessage: '是'
        });
        const No = formatMessage({
            id: 'detailPage.no',
            defaultMessage: '否'
        });
        const partSalesPrice = this.state.data.partSalesPrice || [];
        const partSalesProperty = this.state.data.partSalesProperty || [];
        const partSalesPriceColumns = [{
            title: formatMessage({
                id: 'detailPage.brand',
                defaultMessage: '品牌'
            }),
            dataIndex: 'brandName',
            render: (text, record) => record.brandCode + text,
            sorter: (a, b) => a.brandName - b.brandName
        }, {
            title: formatMessage({
                id: 'detailPage.beginDate',
                defaultMessage: '生效日期'
            }),
            dataIndex: 'beginDate',
            render: text => formatDateTime(text, DATE_FORMAT),
            sorter: (a, b) => moment(a.beginDate) - moment(b.beginDate)
        }, {
            title: formatMessage({
                id: 'detailPage.endDate',
                defaultMessage: '失效日期'
            }),
            dataIndex: 'endDate',
            render: text => formatDateTime(text, DATE_FORMAT),
            sorter: (a, b) => moment(a.endDate) - moment(b.endDate)
        }, {
            title: formatMessage({
                id: 'detailPage.currency',
                defaultMessage: '币种'
            }),
            dataIndex: 'currency',
            render: text => conventEnumValueToString(currency, text),
            sorter: (a, b) => a.currency - b.currency
        }, {
            title: formatMessage({
                id: 'detailPage.price',
                defaultMessage: '价格'
            }),
            dataIndex: 'price',
            render: text => formatAmount(text),
            sorter: (a, b) => a.price - b.price
        }];
        if(!this.props.isDealerUser) {
            partSalesPriceColumns.splice(6, 8, ...[
                {
                    title: formatMessage({
                        id: 'detailPage.isEstimated',
                        defaultMessage: '是否暂估价'
                    }),
                    dataIndex: 'isEstimated',
                    render: text => (text ? Yes : No),
                    sorter: (a, b) => a.isEstimated - b.isEstimated
                },
                {
                    title: formatMessage({
                        id: 'detailPage.dealerCode',
                        defaultMessage: '总代号'
                    }),
                    dataIndex: 'dealerCode',
                    sorter: (a, b) => a.dealerCode - b.dealerCode
                }
            ]);
            partSalesPriceColumns.splice(4, 0, ...[
                {
                    title: formatMessage({
                        id: 'detailPage.type',
                        defaultMessage: '价格类型'
                    }),
                    dataIndex: 'type',
                    render: text => conventEnumValueToString(partsPriceType, text),
                    sorter: (a, b) => a.type - b.type
                }
            ]);
        }
        const partSalesPropertyColums = [{
            title: formatMessage({
                id: 'detailPage.brand',
                defaultMessage: '品牌'
            }),
            dataIndex: 'brandName',
            render: (text, record) => record.brandCode + text
        }, {
            title: formatMessage({
                id: 'detailPage.saleable',
                defaultMessage: '是否可销售'
            }),
            dataIndex: 'saleable',
            render: text => (text ? Yes : No)
        }, {
            title: formatMessage({
                id: 'detailPag.remark',
                defaultMessage: '备注'
            }),
            dataIndex: 'remark',
        }];
        
        const operations = [];
        return (
            <Form className="form-standard">
                <div className="page-toolbar">
                    <Button type="primary" disabled={this.state.isSubmitting} href={`#${routes.query.url()}`}>{
                        formatMessage({
                            id: 'detailPage.return',
                            defaultMessage: '返回'
                        })
                    }</Button>
                </div>
                <Spin spinning={this.state.isFetching || this.state.isSubmitting}>
                    <Modal
                        title={this.props.intl.formatMessage({
                            id: 'modal.title',
                            defaultMessage: '备件详细信息'
                        })}
                        width="350px"
                        maskClosable={false}
                        footer={null}
                        destroyOnClose={true}
                        visible={this.state.visible}
                        onCancel={this.toggle}>
                    </Modal>
                    <Card>
                        <DescriptionList size="large" title={<Row><Col span={12}>{formatMessage({
                            id: 'detailPage.card.title',
                            defaultMessage: '基础信息'
                        })}</Col>
                        <Col className={styles.optionBtn} span={12}>{operations}</Col></Row>} >
                            <Description term={formatMessage({
                                id: 'detailPage.data.code',
                                defaultMessage: '备件编号'
                            })}>{this.state.data.code}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.name',
                                defaultMessage: '备件名称'
                            })}>
                                {this.state.data.name && this.state.data.name.length > 30 ? <Ellipsis tooltip fullWidthRecognition length={30}>{this.state.data.name}</Ellipsis> : this.state.data.name}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.specialName',
                                defaultMessage: '备件专用名称'
                            })}>{this.state.data.specialName}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.description',
                                defaultMessage: '英文描述'
                            })}>{this.state.data.description}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.partCategory',
                                defaultMessage: '备件分类'
                            })}>{this.state.data.partCategory}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.length',
                                defaultMessage: '长'
                            })}>{this.state.data.length}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.width',
                                defaultMessage: '宽'
                            })}>{this.state.data.width}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.height',
                                defaultMessage: '高'
                            })}>{this.state.data.height}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.grossWeight',
                                defaultMessage: '毛重'
                            })}>{this.state.data.grossWeight}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.netWeight',
                                defaultMessage: '净重'
                            })}>{this.state.data.netWeight}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.productCategoryCode',
                                defaultMessage: '车型编号'
                            })}>
                                {this.state.data.productCategoryCode && this.state.data.productCategoryCode.length > 30 ? <Ellipsis tooltip fullWidthRecognition length={30}>{this.state.data.productCategoryCode}</Ellipsis> : this.state.data.productCategoryCode}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.partReplacementCode',
                                defaultMessage: '替代件编号'
                            })}>{this.state.data.partReplacementCode}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.alternativePlan',
                                defaultMessage: '替代方案'
                            })}>{this.state.data.alternativePlan}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.supplierCode',
                                defaultMessage: '首选供应商代码'
                            })}>
                                {this.state.data.supplierCode &&
                                     this.state.data.supplierCode.length > 30
                                    ? <Ellipsis tooltip fullWidthRecognition length={30}>
                                        {this.state.data.supplierCode}</Ellipsis>
                                    : this.state.data.supplierCode}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.unit',
                                defaultMessage: '计量单位'
                            })}>{this.state.data.unit}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.certificationMark',
                                defaultMessage: '认证标识'
                            })}>{this.state.data.certificationMark}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.minPackSize',
                                defaultMessage: '最小包装数'
                            })}>{this.state.data.minPackSize}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.minOrderQuantity',
                                defaultMessage: '最小订购量'
                            })}>{this.state.data.minOrderQuantity}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.usagePerCar',
                                defaultMessage: '每车用量'
                            })}>{this.state.data.usagePerCar}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.isConsume',
                                defaultMessage: '消耗库存'
                            })}>{this.state.data.isConsume}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.isDecimalAllowed',
                                defaultMessage: '是否允许小数'
                            })}>{this.state.data.isDecimalAllowed ? Yes : No}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.overseaOnly',
                                defaultMessage: '是否海外专用'
                            })}>{this.state.data.overseaOnly ? Yes : No}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.shelfLife',
                                defaultMessage: '保质期'
                            })}>{this.state.data.shelfLife}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.safeMaterial',
                                defaultMessage: '安全件'
                            })}>{this.state.data.safeMaterial}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.style',
                                defaultMessage: '样式'
                            })}>{this.state.data.style}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.packageRule',
                                defaultMessage: '包装规则'
                            })}>{this.state.data.packageRule}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.isImported',
                                defaultMessage: '是否进口件'
                            })}>{this.state.data.isImported ? Yes : No}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.status',
                                defaultMessage: '状态'
                            })}>{conventEnumValueToString(partStatus, this.state.data.status)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.chemicalCheck',
                                defaultMessage: '化工鉴定'
                            })}>{this.state.data.chemicalCheck ? Yes : No}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.airMagneticCheck',
                                defaultMessage: '空运磁检'
                            })}>{this.state.data.airMagneticCheck ? Yes : No}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.businessCheck',
                                defaultMessage: '商检'
                            })}>{this.state.data.businessCheck ? Yes : No}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.dangerousGoods',
                                defaultMessage: '空运危险'
                            })}>{this.state.data.dangerousGoods ? Yes : No}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.remoteControl',
                                defaultMessage: '遥控器'
                            })}>{this.state.data.remoteControl ? Yes : No}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.cvJointKit',
                                defaultMessage: '球笼修理包'
                            })}>{this.state.data.cvJointKit ? Yes : No}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.channel',
                                defaultMessage: '渠道'
                            })}>{conventEnumValueToString(partChannel, this.state.data.channel)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.remark',
                                defaultMessage: '备注'
                            })}>{this.state.data.remark}</Description>
                        </DescriptionList>
                    </Card>
                    <Card title={formatMessage({
                        id: 'detailPage.data.partPrice',
                        defaultMessage: '价格清单'
                    })}>
                        <Table
                            className="white-space-nowrap"
                            dataSource={partSalesPrice}
                            rowKey="id"
                            pagination={false}
                            rowClassName={this.setClassName}
                            {...TABLE}
                            columns={partSalesPriceColumns}/>
                    </Card>
                    <Card title={formatMessage({
                        id: 'detailPage.data.partSalesProperty',
                        defaultMessage: '销售属性'
                    })}>
                        <Table
                            className="white-space-nowrap"
                            dataSource={partSalesProperty}
                            rowKey="id"
                            pagination={false}
                            {...TABLE}
                            columns={partSalesPropertyColums}/>
                    </Card>
                </Spin>
            </Form>
        );
    }
}

DetailPage.propTypes = {
    id: PropTypes.string.isRequired,
    isDealerUser: PropTypes.bool.isRequired,
    queryInitData: PropTypes.func.isRequired,
    refreshList: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object,
    match: PropTypes.object,
};

const getDealerUser = selectorFactory(['page', 'domainData', 'initData', 'isDealerUser']);

const mapStateToProps = state => ({
    isDealerUser: getDealerUser(state)
});

const mapDispatchToProps = dispatch => ({
    queryInitData: id => dispatch(actions.getDetailForDetailPage(id)),
    refreshList: () => dispatch(actions.changePageForList()),
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(DetailPage));
